import { useEffect } from "react";
import {
  Card,
  Form,
  Input,
  InputNumber,
  Row,
  Col,
  message,
  Divider,
  Segmented,
  Popover,
  Button,
} from "antd";
import {
  SyncOutlined,
  SaveOutlined,
  ArrowDownOutlined,
} from "@ant-design/icons";
import { invoke } from "@tauri-apps/api/core";
import { useLocation } from "react-router-dom";

import { useLoading } from "../../components/LoadingProvider"; // 引入你的 Loading hook

const Setting = () => {
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const location = useLocation();
  const { showLoading, hideLoading } = useLoading(); // 使用全局 loading

  const validateHost = (_: any, value: string) => {
    if (!value) return Promise.reject("请输入地址");
    if (/^https?:\/\//.test(value)) {
      return Promise.reject("不要包含 http:// 或 https://");
    }
    return Promise.resolve();
  };

  const loadConfig = async () => {
    try {
      const config: any = await invoke("get_setting", {
        path: "client.config",
      });

      if (config.data) {
        form.setFieldsValue({
          server_addr: config.data.server_addr,
          server_port: config.data.server_port,
          client_addr: config.data.client_addr,
          client_port: config.data.client_port,
          client_user: config.data.client_user,
          client_password: config.data.client_password,
          client_server_type: config.data.client_server_type || 2,
          client_server_path: config.data.client_server_path || "",
          client_go: config.data.client_go,
          client_project: config.data.client_project,
        });
        messageApi.success("加载配置");
      }
    } catch (err) {
      messageApi.error("加载配置失败");
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      await invoke("set_setting", { path: "client.config", value: values });
      messageApi.success("配置保存成功");
    } catch (err) {
      console.error(err);
      messageApi.error("配置保存失败，请检查日志");
    }
  };

  useEffect(() => {
    loadConfig();
  }, [location.pathname]);

  return (
    <div>
      {contextHolder}
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        onValuesChange={(_) => form.submit()}
      >
        <Card
          hoverable
          style={{ margin: 24 }}
          actions={[
            <Button
              key="save"
              type="primary"
              icon={<SaveOutlined />}
              onClick={() => form.submit()}
            >
              保存配置
            </Button>,
            <Button
              key="reload"
              type="default"
              icon={<SyncOutlined />}
              onClick={loadConfig}
            >
              重载配置
            </Button>,
          ]}
        >
          {/* 服务端配置 */}
          <Divider orientation="left">服务端配置</Divider>
          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                label="服务端地址"
                name="server_addr"
                rules={[
                  { required: true, message: "请输入服务端地址" },
                  { validator: validateHost },
                ]}
              >
                <Input placeholder="例如：frp.example.com 或 127.0.0.1" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                label="服务端端口"
                name="server_port"
                rules={[
                  { required: true, message: "请输入端口" },
                  {
                    type: "number",
                    min: 1,
                    max: 65535,
                    message: "端口范围 1~65535",
                  },
                ]}
              >
                <InputNumber style={{ width: "100%" }} placeholder="7000" />
              </Form.Item>
            </Col>
          </Row>

          {/* <Form.Item label="启动命令" name="startCmd">
            <Input placeholder="例如：frpc -c frpc.toml" />
          </Form.Item> */}

          {/* 客户端配置 */}
          <Divider orientation="left">客户端配置</Divider>
          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                label="客户端 WEB 地址"
                name="client_addr"
                rules={[
                  { required: true, message: "请输入客户端地址" },
                  { validator: validateHost },
                ]}
              >
                <Input placeholder="例如：frp.example.com 或 127.0.0.1" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                label="客户端 WEB 端口"
                name="client_port"
                rules={[
                  { required: true, message: "请输入端口" },
                  {
                    type: "number",
                    min: 1,
                    max: 65535,
                    message: "端口范围 1~65535",
                  },
                ]}
              >
                <InputNumber style={{ width: "100%" }} placeholder="7000" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                label="客户端用户"
                name="client_user"
                rules={[{ required: false, message: "请输入客户端用户名" }]}
              >
                <Input placeholder="例如：admin" />
              </Form.Item>
            </Col>
            <Col xs={24} sm={12}>
              <Form.Item
                label="客户端密码"
                name="client_password"
                rules={[{ required: false, message: "请输入客户端密码" }]}
              >
                <Input placeholder="例如：admin" />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">客户端启动方式</Divider>
          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                label="启动方式"
                name="client_server_type"
                rules={[{ required: true, message: "请选择启动方式" }]}
                getValueFromEvent={(val) => val} // ✅ 让 Form 正确拿到 Segmented 的值
              >
                <Segmented
                  options={[
                    {
                      label: (
                        <div style={{ padding: 4 }}>
                          <div>根项目</div>
                        </div>
                      ),
                      value: 1,
                    },
                    {
                      label: (
                        <div style={{ padding: 4 }}>
                          <div>预编译</div>
                        </div>
                      ),
                      value: 2,
                    },
                  ]}
                />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item shouldUpdate>
            {({ getFieldValue }) =>
              getFieldValue("client_server_type") === 1 ? (
                <Row gutter={16}>
                  <Col xs={24} sm={12}>
                    <Form.Item
                      label="Go 命令路径"
                      name="client_go"
                      rules={[
                        { required: true, message: "请输入 Go 命令路径" },
                      ]}
                    >
                      <Input placeholder="例如：/usr/local/go/bin/go" />
                    </Form.Item>
                  </Col>
                  <Col xs={24} sm={12}>
                    <Form.Item
                      label="FRPC 项目路径"
                      name="client_project"
                      rules={[
                        { required: true, message: "请输入 FRP 项目路径" },
                      ]}
                    >
                      <Input placeholder="例如：/Users/username/frp-client" />
                    </Form.Item>
                  </Col>
                </Row>
              ) : (
                <Col xs={24} sm={24}>
                  <Form.Item
                    label="FRPC 可执行文件"
                    name="client_server_path"
                    rules={[
                      { required: true, message: "请输入 frpc 可执行文件" },
                    ]}
                  >
                    <Input
                      placeholder="FRPC 可执行文件路径"
                      onChange={(e) =>
                        form.setFieldsValue({
                          client_server_path: e.target.value,
                        })
                      }
                      suffix={
                        <Popover content="点击下载预编译包!" trigger="hover">
                          <ArrowDownOutlined
                            style={{
                              color: "#fa8c16",
                              cursor: "pointer",
                              fontSize: 16,
                            }}
                            title="点击下载预编译包"
                            onClick={async () => {
                              if (form.getFieldValue("client_server_path")) {
                                messageApi.error("请先清空frpc客户端路径");
                                return;
                              }
                              showLoading();
                              const result: any = await invoke(
                                "download_and_extract_frpc"
                              ); // 下载函数返回路径
                              hideLoading();
                              if (!result.code) {
                                messageApi.error("下载失败！");
                                return;
                              }
                              form.setFieldsValue({
                                client_server_path: result.data,
                              });
                            }}
                          />
                        </Popover>
                      }
                    />
                  </Form.Item>
                </Col>
              )
            }
          </Form.Item>
        </Card>
      </Form>
    </div>
  );
};

export default Setting;
